/**
 *  * @author QinGuan
 *  * @date:2015-12-25 下午02:26:26
 *  * @version :3.0
 *  *
 *  
 */
package com.ctvit.wsservice.basedata.service;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.*;

import com.ctvit.framework.util.HttpUtils;
import com.ctvit.wsservice.basedata.domain.ZcdmTFinalitemWithBLOBs;
import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;

import com.ctvit.common.FileService;
import com.ctvit.framework.common.DateJsonValueProcessor;
import com.ctvit.framework.dao.Condition;
import com.ctvit.framework.dao.OrderPart;
import com.ctvit.framework.service.BaseService;
import com.ctvit.framework.web.context.ContextHolder;
import com.ctvit.sms.platform.service.ContentLogService;
import com.ctvit.struts.common.CommonFunc;
import com.ctvit.wsservice.basedata.domain.Channelzone;
import com.ctvit.wsservice.basedata.domain.ZcdmTDireCoor;
import com.ctvit.wsservice.basedata.domain.ZcdmTDiresend;
import com.ctvit.wsservice.basedata.domain.ZcdmTLive;
import com.ctvit.wsservice.basedata.domain.ZcdmTLiveCoor;
import com.ctvit.wsservice.basedata.domain.ZcdmTLongCoor;
import com.ctvit.wsservice.basedata.domain.ZcdmTLongSend;
import com.ctvit.wsservice.basedata.domain.ZcdmTLonglist;
import com.ctvit.wsservice.basedata.domain.ZcdmTLonglive;
import com.ctvit.wsservice.basedata.domain.ZcdmTProglist;
import com.ctvit.wsservice.basedata.domain.ZcdmTProgplaystatus;
import com.ctvit.wsservice.basedata.domain.ZcdmTProrec;
import com.ctvit.wsservice.basedata.domain.ZcdmTSubj;
import com.ctvit.wsservice.basedata.domain.ZppmTProginfo;
import com.ctvit.wsservice.basedata.domain.ZppmTask;
import org.apache.log4j.Logger;
import org.json.JSONObject;

@SuppressWarnings("serial")
public class TaskReceiveService extends BaseService {

    private static final Logger LOGGER = Logger.getLogger(TaskReceiveService.class);

    private Properties properties = new Properties();


    /**
     * @param zcdmTSubj
     * @ps:插入数据
     */
    public boolean save(ZcdmTSubj zcdmTSubj) {
        if (zcdmTSubj == null) // 阻止无效参数
            return false;
        Condition condition = new Condition();
        condition.add("zSubjCd", zcdmTSubj.getZSubjCd());
        if (genericDao.updateByCondition(zcdmTSubj, null, condition) == 0) {
            genericDao.insert(zcdmTSubj);
        }
        return true;
    }

    /**
     * 接收给媒资的入库任务，以及节目主数据信息
     *
     * @param zppmTask
     * @param zppmTProginfo
     * @return
     */
    public int saveProgInfo(ZppmTask zppmTask, ZppmTProginfo zppmTProginfo) {
        int ret = 0;
        Condition condition = new Condition();
        condition.add("zTaskId", zppmTask.getZTaskId());
        int cnt = genericDao.updateByCondition(zppmTask,
                new String[]{"zTaskId"}, condition);
        if (cnt > 0) {
            ret = -1;// 已经存在，不再接收
        } else {
            genericDao.insert(zppmTask);
            condition = new Condition();
            condition.add("zAudVer", zppmTProginfo.getZAudVer());
            condition.add("zCapVer", zppmTProginfo.getZCapVer());
            condition.add("zProcode", zppmTProginfo.getZProcode());
            cnt = genericDao.updateByCondition(zppmTProginfo, new String[]{
                    "zProcode", "zAudVer", "zCapVer"}, condition);
            if (cnt == 0) {
                zppmTProginfo.setCreateTimestamp(new Timestamp(Calendar.getInstance().getTimeInMillis()));
                genericDao.insert(zppmTProginfo);
            } else {// 任务反馈结束后，同一个节目代码还可能修改，此时再次下达入库任务
                genericDao.update(zppmTProginfo, new String[]{"zSubjCd",
                        "zPgnam", "zTimeEstm"});
            }
        }
        return ret;
    }

    /**
     * @param zcdmTProrec
     * @return -1 参数异常 0插入成功 1更新失败
     * @ps: 节目播出单插入数据库(主表和子表)
     */
    public int save(ZcdmTProrec zcdmTProrec, List<ZcdmTProglist> list) {
        if (zcdmTProrec == null && list == null)
            return -1; // 参数异常!
        Condition condition = new Condition();
        condition.add("zProRecCd", zcdmTProrec.getZProRecCd());
        if (genericDao.updateByCondition(zcdmTProrec, null, condition) == 0) {
            genericDao.insert(zcdmTProrec);
            genericDao.batchInsert(list);
            //编排单信息下发8K运管平台
            List<Map<String, Object>> proglistMaps = convertPoToMap(list);
            JSONObject proglistJson = new JSONObject();
            proglistJson.put("cdmProglistDTOS", proglistMaps);
            try {
                InputStream inputStream = ContextHolder.class.getResourceAsStream("/config/yygl.properties");
                properties.load(inputStream);
                String proglistYyglUrl = properties.getProperty("yygl.proglistYyglUrl");
                String method = properties.getProperty("yygl.method");
                Integer tryNum = Integer.parseInt(properties.getProperty("yygl.tryNum"));
                HttpUtils.JsonHttpRequestPost(proglistYyglUrl, method, proglistJson, tryNum);
            } catch (IOException e) {
                LOGGER.error("编排单信息下发运管平台失败", e);
            }

            return 0; // 插入成功!
        }
        return 1; // 信息未更新!

    }

    private List<Map<String, Object>> convertPoToMap(List<ZcdmTProglist> list) {
        List<Map<String, Object>> yyglProglists = new ArrayList<>();
        for (ZcdmTProglist proglist : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("chanlCd", proglist.getZChanlCd());
            map.put("subjCd", proglist.getZPlaySubjCd());
            map.put("procode", proglist.getZProcode());
            map.put("pgnam", proglist.getZPgnam());
            map.put("playTime", proglist.getZPlayTime());
            map.put("playDate", proglist.getZPlayDate());
            map.put("proRtmlen", proglist.getZProRtmlen());
            map.put("isAd", proglist.getZIsAd());
            yyglProglists.add(map);
        }
        return yyglProglists;
    }

    /**
     * @param zcdmTLive
     * @param list
     * @return -1 参数异常 0插入成功 1更新失败
     * @ps:
     */
    public int save(ZcdmTLive zcdmTLive, List<ZcdmTLiveCoor> list) {
        if (zcdmTLive == null && list == null)
            return -1;// 数据有异常!
        Condition condition = new Condition();
        condition.add("zLiveCd", zcdmTLive.getZLiveCd());
        if (genericDao.updateByCondition(zcdmTLive, null, condition) == 0) {
            genericDao.insert(zcdmTLive);
            genericDao.batchInsert(list);
            return 0;// 数据已插入!
        }
        return 1; // 数据未更新!

    }

    /**
     * @param zcdmTDiresend
     * @param listDireCoors
     * @return -1 参数异常 0插入成功 1更新失败
     * @ps:
     */
    public int save(ZcdmTDiresend zcdmTDiresend,
                    List<ZcdmTDireCoor> listDireCoors) {
        if (zcdmTDiresend == null && listDireCoors == null)
            return -1;
        Condition condition = new Condition();
        ZcdmTProglist zcdmTProglist = new ZcdmTProglist();// 节目单子表
        zcdmTProglist.setZInForm("1");// 修改成直送
        condition.add("zPlayDate", zcdmTDiresend.getZPlayDate());
        condition.add("zChanlCd", zcdmTDiresend.getZChanlCd());
        condition.add("zAudVer", zcdmTDiresend.getZAudVer());
        genericDao.updateByCondition(zcdmTProglist, new String[]{"zInForm"},
                condition);
        condition = new Condition();
        condition.add("zDiresendCd", zcdmTDiresend.getZDiresendCd());
        if (genericDao.updateByCondition(zcdmTDiresend, null, condition) == 0) {
            genericDao.insert(zcdmTDiresend);
            genericDao.batchInsert(listDireCoors);
            return 0;
        }
        return 1;
    }

    /**
     * @param zcdmTLongSend
     * @param listLongCoors
     * @return
     * @ps:长效播送单
     */
    public int save(ZcdmTLongSend zcdmTLongSend,
                    List<ZcdmTLongCoor> listLongCoors) {
        if (zcdmTLongSend == null && listLongCoors == null)
            return -1;
        Condition condition = new Condition();
        condition.add("zDiresendCd", zcdmTLongSend.getZDiresendCd());
        if (genericDao.updateByCondition(zcdmTLongSend, null, condition) == 0) {
            genericDao.insert(zcdmTLongSend);
            genericDao.batchInsert(listLongCoors);
            return 0;
        }
        return 1;
    }

    /**
     * @param zcdmTLonglive
     * @param longlists
     * @param liveCoors
     * @return
     * @ps:长效直播单及其子表
     */
    public int save(ZcdmTLonglive zcdmTLonglive, List<ZcdmTLonglist> longlists,
                    List<ZcdmTLiveCoor> liveCoors) {
        if (zcdmTLonglive == null && longlists == null && liveCoors == null)
            return -1;
        Condition condition = new Condition();
        condition.add("zLiveLongCd", zcdmTLonglive.getZLiveLongCd());
        if (genericDao.updateByCondition(zcdmTLonglive, null, condition) == 0) {
            genericDao.insert(zcdmTLonglive);
            genericDao.batchInsert(longlists);
            genericDao.batchInsert(liveCoors);
            return 0;
        }
        return 1;
    }

    /**
     * @return
     * @ps:根据栏目代码更新最新的一条信息的是否有效的标志列为"X"
     */
    public boolean isValid(String ZsubjCd) {
        if (ZsubjCd == null) {
            return false;
        }
        Condition condition = new Condition();
        ZcdmTLonglive zcdmTLonglive = new ZcdmTLonglive();
        zcdmTLonglive.setZSubjCd(ZsubjCd);
        condition.add("zSubjCd", zcdmTLonglive.getZSubjCd());
        zcdmTLonglive = genericDao.getByCondition(zcdmTLonglive.getClass(),
                condition, new OrderPart().add("zCrtim", "DESC")).get(0);// 得到最新的一条记录
        Condition conditionOth = new Condition();
        zcdmTLonglive.setZIsValid("X");// 设置为无效
        conditionOth.add("zIsValid", zcdmTLonglive.getZIsValid());
        int i = genericDao.updateByCondition(zcdmTLonglive,
                new String[]{"zIsValid"}, conditionOth);
        if (i > 0) {
            // 更新成功!
            return true;
        }
        return false;
    }


    public int save(ZcdmTProgplaystatus zcdmTProgplaystatus) {
        if (zcdmTProgplaystatus == null)
            return -1;
        Condition condition = new Condition();
        condition.add("id", zcdmTProgplaystatus.getId());
        Long pk = genericDao.insert(zcdmTProgplaystatus);
        String statCode = zcdmTProgplaystatus.getZPalystatCode();
//		if ("2".equals(statCode)||"3".equals(statCode)||"4".equals(statCode)){
//			File[] fs=FileService.getFiles(CommonFunc.nasFileDir, "*"+zcdmTProgplaystatus.getZProcode()+"*.*");
//			for (int i = 0; i < fs.length; i++) {
//				try {
//					fs[i].delete();
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
//			}
//          statCode = 1，可播， 2,禁播，3暂停播出，只有在2禁播，3暂停播出可调链接。
        if ("2".equals(statCode) || "3".equals(statCode)) {

//			File[] fs=FileService.getFiles(CommonFunc.nasFileDir, "*"+zcdmTProgplaystatus.getZProcode()+"*.*");
//			for (int i = 0; i < fs.length; i++) {
//				try {
//					fs[i].delete();
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
//			}
            try {
                File[] fs = FileService.getFiles(CommonFunc.nasFileDir, "*" + zcdmTProgplaystatus.getZProcode() + "*.*");
                for (int i = 0; i < fs.length; i++) {
                    fs[i].delete();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            //
            String jsonString = "";
            HashMap mapid = new HashMap();
            mapid.put("id", zcdmTProgplaystatus.getZProcode());
            JSONArray jsonArray = JSONArray.fromObject(mapid);
            jsonString = CommonFunc.dealWithFirstChar(jsonArray.toString());

            //调用url发布
            CommonFunc.postJsonTo(jsonString, null);


//			String sqlString="delete from t_channelzone where f_procode='"+zcdmTProgplaystatus.getZProcode()+"'";
//			genericDao.updateBySqlStr(sqlString);
//			sqlString="select distinct f_chanl_cd,f_crtuser from t_channelzone where f_procode='"+zcdmTProgplaystatus.getZProcode()+"'";
//			List<Map<String,?>> lst=genericDao.executeSql(sqlString);
//			String chanlCd="",crtUser="";Channelzone channelzone=new Channelzone();List listChanlZoneBean=null;String jsonString="";
//			ContentLogService contentLogService=ContextHolder.getBean(ContentLogService.class);
//			for (Map<String, ?> map : lst) {
//				chanlCd=(String)map.get("f_chanl_cd");
//				crtUser=(String)map.get("f_crtuser");
//				channelzone.setChanlCd(chanlCd);
//				channelzone.setCrtuser(crtUser);
//				listChanlZoneBean=contentLogService.getChanlZoneBeansList(channelzone,1,999);
//				JsonConfig cfg = new JsonConfig();
//				cfg.registerJsonValueProcessor(java.sql.Timestamp.class,new DateJsonValueProcessor());
//				JSONArray jsonArray = JSONArray.fromObject(listChanlZoneBean, cfg);
//				jsonString=CommonFunc.dealWithFirstChar(jsonArray.toString());
//				//调用url发布
//				CommonFunc.postJsonTo(jsonString);
//			}

        }
        return 0; // 插入成功!
    }

}
